package cn.zwx.zookeeper.config.example.source;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

/**
 * 参考 PropertySourceLocator springboot<2.4 实现
 * @author zhangwenxue
 */
public interface PropertySourceLocator {

    /**
     * 加载属性源
     * @param environment 环境类
     * @param applicationContext 容器
     * @return 返回资源列表
     */
    PropertySource<?> locate(Environment environment, ConfigurableApplicationContext applicationContext);

    /**
     * 加载属性源 默认实现
     * @param environment 环境类
     * @param applicationContext 容器
     * @return 返回资源列表
     */
    default Collection<PropertySource<?>> locateCollection(Environment environment, ConfigurableApplicationContext applicationContext){
        return locateCollections(this,environment,applicationContext);
    }

    /**
     * 收集属性源列表
     * @param locator  locator
     * @param environment 环境类
     * @param applicationContext 容器
     * @return 返回资源列表
     */
    static Collection<PropertySource<?>> locateCollections(PropertySourceLocator locator,Environment environment, ConfigurableApplicationContext applicationContext) {
        PropertySource<?> propertySource=locator.locate(environment,applicationContext);
        if(propertySource==null){
            return Collections.emptyList();
        }
        return Arrays.asList(propertySource);
    }

}
